package com.ljkj.cordial.chat.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.MsgType;
import com.ljkj.cordial.chat.bean.PayLoad;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.widget.PuzzleImageView;
import com.nic.view.util.SharedUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.github.rockerhieu.emojicon.EmojiconTextView;

public class NavChatRecycleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final static int FRIEND = 0;
    private final static int GROUP = 1;
    private List<ChatContentTable> list = new ArrayList<>();
    private int[] payloads;
    private int lastPosition;
    private boolean loadAccess;
    private String nickName;

    private Map<Integer, Long> map = new HashMap<>();
    private int lastIsTopPosition = 0;

    public int getLastIsTopPosition() {
        return lastIsTopPosition;
    }

    public void setList(List<ChatContentTable> list, int... payload) {
        try {
            if (list == null || list.isEmpty()) {
                return;
            }
//            this.list = new ArrayList<>();
//            for (Iterator<ChatContentTable> it = list.iterator(); it.hasNext(); ) {
//                ChatContentTable item = it.next();
//                if (item.getIsTOP() == 1) {
//                    this.list.add(item);
//                    it.remove();
//                }
//            }
//            if (!this.list.isEmpty()) {
//                Collections.sort(this.list, comparatorTop);
//            }
            this.list = list;
            this.payloads = payload;
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserTableBean u = UserTableBean.getCurrentUser();
        if (u != null) {
            nickName = u.getNickname();
        }
//        saveSort(getList());
        updateLastTopPosition();
    }

//    public static Comparator<ChatContentTable> comparator = new Comparator<ChatContentTable>() {
//        @Override
//        public int compare(ChatContentTable o1, ChatContentTable o2) {
//            if (o2.getUpdateTime() - o1.getUpdateTime() < 0) {
//                return -1;
//            } else if (o2.getUpdateTime() - o1.getUpdateTime() > 0) {
//                return 1;
//            }
//            return 0;
//        }
//    };
//    public static Comparator<ChatContentTable> comparatorTop = new Comparator<ChatContentTable>() {
//        @Override
//        public int compare(ChatContentTable o1, ChatContentTable o2) {
//            if (o2.getUpdateTopTime() - o1.getUpdateTopTime() < 0) {
//                return -1;
//            } else if (o2.getUpdateTopTime() - o1.getUpdateTopTime() > 0) {
//                return 1;
//            }
//            return 0;
//        }
//    };

    private void updateLastTopPosition() {
        int c = (int) ChatContentTable.queryTopSortListCount();
        lastIsTopPosition = c == 0 ? c : c - 1;
    }

//    public void saveSort(List<ChatContentTable> list) {
//        ObserverThread.create().onBackGroudThread(() -> {
//            map.clear();
//            boolean isTop = false;
//            for (int i = 0; i < list.size(); i++) {
//                ChatContentTable chat = list.get(i);
//                if (chat == null) {
//                    continue;
//                }
//                if (chat.getIsTOP() == 1) {
//                    lastIsTopPosition = i;
//                    isTop = true;
//                }
//                map.put(i, chat.getId());
//            }
//            if (!isTop) {
//                lastIsTopPosition = 0;
//            }
//        });

//    }

//    public void reSort(List<ChatContentTable> list, int... payload) {
//        List<ChatContentTable> contentTables = new ArrayList<>();
//        int len = list.size();
//        for (int i = 0; i < len; i++) {
//            ChatContentTable c = ChatContentTable.queryRowById(map.get(i));
//            if (c != null) {
//                contentTables.add(c);
//            }
//        }
//        setList(contentTables, payload);
//    }

    private String getAtelNickName() {
        return "@" + nickName + " ";
    }

    public List<ChatContentTable> getList() {
        return list;
    }


    public void notifyData() {
        if (payloads == null || payloads.length == 0) {
            notifyItemRangeChanged(0, getItemCount(), PayLoad.create());
        } else {
            notifyItemRangeChanged(0, getItemCount(), PayLoad.create(payloads));
        }

    }

    @Override
    public int getItemViewType(int position) {
        ChatContentTable item = list.get(position);
        if (Canstants.GROUP_CHAT == item.getChatType()) {
            return GROUP;
        }
        return FRIEND;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View convertView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_nav_chat, null, false);
        ContentViewHolder holder = new ContentViewHolder(convertView);
        if (i == GROUP) {
            holder.piv.setImageResource(R.mipmap.pic_group_avatar_default_58dp);
        } else {
            holder.piv.setImageResource(R.mipmap.pic_user_avatar_default_36dp);
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int i) {
        ContentViewHolder viewHolder = (ContentViewHolder) holder;
        Context context = viewHolder.itemView.getContext();
        ChatContentTable item = list.get(i);
        if (item == null) {
            return;
        }
        viewHolder.itemView.setBackgroundResource(item.getIsTOP() == 1 ? R.color.gray2 : R.color.white);
//        if (Canstants.GROUP_CHAT == item.getChatType()) {
//            viewHolder.ivIsVisitor.setVisibility(View.GONE);
//            viewHolder.tvTan.setVisibility(View.GONE);
//        } else if (Canstants.SINGLE_CHAT == item.getChatType()) {
//            if (IMSContacts.UserType.TOURISTS_USER.equals(item.getTargetType())) {
//                viewHolder.ivIsVisitor.setVisibility(View.VISIBLE);
//                viewHolder.tvContent.setVisibility(View.VISIBLE);
//                viewHolder.tvContent.setText("此好友是游客身份，请注意安全");
//            } else {
//                viewHolder.ivIsVisitor.setVisibility(View.GONE);
//                viewHolder.tvTan.setVisibility(View.GONE);
//            }
//
//        }
        viewHolder.tvTitle.setText(TextUtils.isEmpty(item.getAlias()) ? item.getTargetName() : item.getAlias());

        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(v, i, item);
                    lastPosition = i;
                }
            }
        });
        viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemLongClick(v, i, item);
                    return true;
                }
                return false;
            }
        });
        text(viewHolder, (Activity) context, item);
        avatarNet(viewHolder, item);

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        if (payloads != null && !payloads.isEmpty()) {
            Object obj = payloads.get(0);
            ContentViewHolder viewHolder = (ContentViewHolder) holder;
            Context context = viewHolder.itemView.getContext();
            ChatContentTable item = list.get(position);
            if (item == null) {
                return;
            }
            if (obj instanceof PayLoad) {
                PayLoad payLoad = (PayLoad) obj;
//            int type = getItemViewType(position);
                for (int type : payLoad.getType()) {
                    if (PayLoad.TEXT == type) {
                        text(viewHolder, (Activity) context, item);
                    }
                    if (PayLoad.AVATAR == type) {
                        avatarNet(viewHolder, item);
                    }
                }
            }
            refreshUnreadSumAndUpdateTime(viewHolder, item);
        } else {
            onBindViewHolder(holder, position);
        }
    }


    private void avatarNet(ContentViewHolder viewHolder, ChatContentTable item) {
        if (Canstants.GROUP_CHAT == item.getChatType()) {
            if (!TextUtils.isEmpty(item.getTargetAvatarPath())) {
                viewHolder.piv.setGroupPaths(item.getTargetAvatarPath());
            } else {
                if (!TextUtils.isEmpty(item.getTargetAvatarUrl()) && !TextUtils.isEmpty(item.getTargetMemberUserId())) {
                    viewHolder.piv.setImageBackGround(item.getTargetAvatarUrl(), item.getTargetMemberUserId());
                } else {
                    viewHolder.piv.setImageResource(R.mipmap.pic_group_avatar_default_58dp);
                }
            }

        } else if (Canstants.SINGLE_CHAT == item.getChatType()) {
            if (!TextUtils.isEmpty(item.getTargetAvatarPath())) {
                viewHolder.piv.setFriendPath(item.getTargetAvatarPath(), item.getTargetAvatarUrl());
            } else {
                viewHolder.piv.setFriendUrl(item.getTargetAvatarUrl(), item.getTargetId());
            }
        }
    }

    private void text(ContentViewHolder viewHolder, Activity context, ChatContentTable item) {

        String draft = (String) SharedUtils.get(context, item.getTargetId(), "");
        if (TextUtils.isEmpty(draft)) {
//            if (item.getReceiveFrom() == UserChatTable.RECEIVE_FROM_NET && !TextUtils.isEmpty(item.getAtelIds()) && item.getAtelIds().contains(UserPreferences.getUserId())) {
//                viewHolder.tvTan.setText("[有人@我]");
//                viewHolder.tvTan.setVisibility(View.VISIBLE);
//            } else {
//                viewHolder.tvTan.setVisibility(View.GONE);
//            }

            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Boolean>() {
                @Override
                public void onAction(Boolean obj) {
                    if (obj != null && obj) {
                        viewHolder.tvTan.setText("[有人@我]");
                        viewHolder.tvTan.setVisibility(View.VISIBLE);
                    } else {
                        viewHolder.tvTan.setVisibility(View.GONE);
                    }
                }

                @Override
                public Boolean onThreadAction() {
                    return ChatTableBean.hasUnreadAt(item.getChatType(), item.getTargetId());
                }
            });
        } else {
            viewHolder.tvTime.setText("");
            viewHolder.tvContent.setText(draft);
//            EmojiPackage.handlerTextThread(context, draft, new EmojiPackage.OnHandlerThreadListener() {
//                @Override
//                public void deCodeMsg(CharSequence text) {
//                    viewHolder.tvContent.setText(text);
//                }
//            });
            viewHolder.tvTan.setText("[草稿]");
            viewHolder.tvTan.setVisibility(View.VISIBLE);
            return;
        }
        if (item.getLastMsgType() == MsgType.Text) {
            if (item.getIsSnapchat() == 0) {
                if (TextUtils.isEmpty(item.getLastMsg())) {
                    viewHolder.tvContent.setText("");
                    viewHolder.tvTime.setText("");
                } else {
                    viewHolder.tvContent.setText(item.getLastMsg());
//                    EmojiPackage.handlerTextThread(context, item.getLastMsg(), new EmojiPackage.OnHandlerThreadListener() {
//                        @Override
//                        public void deCodeMsg(CharSequence text) {
//                            viewHolder.tvContent.setText(text);
//                        }
//                    });

                }
            } else {
                if (TextUtils.isEmpty(item.getLastMsg())) {
                    viewHolder.tvContent.setText("");
//                    viewHolder.tvTime.setText("");
                } else {
                    viewHolder.tvContent.setText("[阅后即焚消息]");
                }
            }

        } else {
            viewHolder.tvContent.setText(getContent(item.getLastMsgType()));
        }
        refreshUnreadSumAndUpdateTime(viewHolder, item);
    }

    private void refreshUnreadSumAndUpdateTime(ContentViewHolder viewHolder, ChatContentTable item) {
        long count = ChatTableBean.queryUnreadChatCount(item.getChatType(), item.getTargetId());
        if (count == 0) {
            viewHolder.tvNum.setVisibility(View.GONE);
        } else {
            viewHolder.tvNum.setVisibility(View.VISIBLE);
            viewHolder.tvNum.setText("" + count);
        }

        viewHolder.tvTime.setText(MsgType.getLastMsgTime(item.getUpdateTime()));
    }

    public void refreshText(int position) {
        notifyItemChanged(position, PayLoad.create(PayLoad.TEXT));
    }

    public void refreshTextAll() {
        notifyItemRangeChanged(0, list.size(), PayLoad.create(PayLoad.TEXT));
    }

    public void refreshAvatar(int position) {
        notifyItemRangeChanged(position, 1, PayLoad.create(PayLoad.AVATAR));
    }

    public void refreshAvatarAndText(int position) {
        notifyItemRangeChanged(position, 1, PayLoad.create());
    }

    public void refreshAvatarAll() {
        notifyItemRangeChanged(0, list.size(), PayLoad.create(PayLoad.AVATAR));
    }

    public void refreshAll() {
        notifyItemRangeChanged(0, list.size(), PayLoad.create(PayLoad.TEXT, PayLoad.AVATAR));
    }

    public void add(ChatContentTable add) {
        this.list.add(add);
        notifyItemInserted(list.size() - 1);
        notifyItemChanged(list.size() - 1, PayLoad.create(PayLoad.AVATAR, PayLoad.TEXT));
    }

    public void remove(int position) {
        if (position >= 0 && position < this.list.size()) {
            this.list.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, getItemCount(), PayLoad.create());
        }
    }

    public void update(int position, ChatContentTable add) {
        if (position >= 0 && position < this.list.size()) {
            ChatContentTable c = this.list.get(position);
            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Object>() {
                @Override
                public void onAction(Object obj) {
                    notifyItemChanged(position, PayLoad.create(PayLoad.AVATAR, PayLoad.TEXT));
                }

                @Override
                public Object onThreadAction() {
                    ChatContentTable.copy(c, add);
                    ChatContentTable.update(c);
                    return null;
                }
            });
        }

    }

    public void itemMove(int fromPosition, boolean isTop) {
        if (getList().get(fromPosition).getIsTOP() == 1 || isTop) {
            itemMove(fromPosition, 0);
            if (onToTopRefreshListener != null) {
                onToTopRefreshListener.onRefreshToTop();
            }
        } else {
            int toPosition = lastIsTopPosition + 1;
            if (lastIsTopPosition == 0) {
                toPosition = 0;
            }
            if (toPosition < getItemCount()) {
                itemMove(fromPosition, toPosition);
            }
        }

    }

    public void cancelTop(int fromPosition) {
        int toPosition = getMiddleTimePosition(this.list.get(fromPosition).getUpdateTime());
        this.list.add(toPosition, this.list.remove(fromPosition));//数据更换
        notifyItemMoved(fromPosition, toPosition);//执行动画
        notifyItemRangeChanged(Math.min(fromPosition, toPosition), Math.abs(fromPosition - toPosition) + 1);
//        saveSort(getList());
        updateLastTopPosition();
    }

    private void itemMove(int fromPosition, int toPosition) {
        this.list.add(toPosition, this.list.remove(fromPosition));//数据更换
        notifyItemMoved(fromPosition, toPosition);//执行动画
        notifyItemRangeChanged(Math.min(fromPosition, toPosition), Math.abs(fromPosition - toPosition) + 1);
//        saveSort(getList());
        updateLastTopPosition();
    }

    public void update(ChatContentTable add) {
        try {
            for (int i = 0; i < getList().size(); i++) {
                ChatContentTable table = getList().get(i);
                if (add.getId() == table.getId()) {
                    getList().set(i, add);
                    if (add.getIsTOP() == 1) {
                        if (i != 0 && ChatContentTable.queryTopgt(add.getUpdateTopTime())) {
                            itemMove(i, true);
                        } else {
                            notifyItemChanged(i, PayLoad.create(PayLoad.AVATAR, PayLoad.TEXT));
                        }
                        return;
                    } else {
                        if (i != 0 && ChatContentTable.queryNormalgt(add.getUpdateTime())) {
                            itemMove(i, false);
                        } else {
                            notifyItemChanged(i, PayLoad.create(PayLoad.AVATAR, PayLoad.TEXT));
                        }
                        return;
                    }
                }
            }
            add(add);
            itemMove(getList().size() - 1, false);
        } catch (Exception e) {
        }
    }


    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    private String getContent(int msgType) {
        String text = "";
        if (MsgType.Picture == msgType) {
            text = "图片";
        } else if (MsgType.Voice == msgType) {
            text = "语音";
        } else if (MsgType.Video == msgType) {
            text = "视频";
        } else if (MsgType.ANNEX == msgType) {
            text = "附件";
        } else if (MsgType.Read_Finish == msgType) {
            text = "消息已焚毁";
        } else if (MsgType.Del_Chat_Msg == msgType || MsgType.History_Time == msgType) {
            text = "";
        }

        return TextUtils.isEmpty(text) ? "" : String.format("[%s]", text);
    }

    public void clear() {
        if (this.list != null) {
            this.list.clear();
            notifyDataSetChanged();
        }
    }

    public Map<Long, Integer> getMap() {
        Map<Long, Integer> map = new HashMap<>();
        for (int i = 0; i < getList().size(); i++) {
            ChatContentTable table = getList().get(i);
            map.put(table.getId(), i);
        }
        return map;
    }

    public int getMiddleTimePosition(long currentTime) {
        int nCount = (int) ChatContentTable.queryNormalgtCount(currentTime);
        return getLastIsTopPosition() + nCount;
    }

    public void setLoadAccess(boolean loadAccess) {
        this.loadAccess = loadAccess;
    }

    public boolean getLoadAccess() {
        return loadAccess;
    }

    public void setPayLoad(int pastVisibleItem, int visibleItemCount) {
        notifyItemRangeChanged(pastVisibleItem, visibleItemCount, PayLoad.create());
    }

    static
    class ContentViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.piv)
        PuzzleImageView piv;
        @BindView(R.id.iv_is_visitor)
        ImageView ivIsVisitor;
        @BindView(R.id.tv_num)
        TextView tvNum;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.tv_content)
        EmojiconTextView tvContent;
        @BindView(R.id.tv_tan)
        TextView tvTan;
        @BindView(R.id.tv_time)
        TextView tvTime;

        ContentViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
//            setIsRecyclable(false);
        }
    }

    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(View v, int position, ChatContentTable item);

        void onItemLongClick(View v, int position, ChatContentTable item);
    }

    private OnToTopRefreshListener onToTopRefreshListener;

    public void setOnToTopRefreshListener(OnToTopRefreshListener onToTopRefreshListener) {
        this.onToTopRefreshListener = onToTopRefreshListener;
    }

    public interface OnToTopRefreshListener {
        void onRefreshToTop();
    }

    private OnToUpdateDataRefreshListener onToUpdateDataRefreshListener;

    public void setOnToUpdateDataRefreshListener(OnToUpdateDataRefreshListener onToUpdateDataRefreshListener) {
        this.onToUpdateDataRefreshListener = onToUpdateDataRefreshListener;
    }

    public interface OnToUpdateDataRefreshListener {
        void onRefreshToUpdateData(int fromPosition, boolean isTop, boolean isMove);
    }
}
